package com.future.mashibing.class02;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;


public class Code03_Comparetor {

    public static void main(String[] args) {
        User user = new User(100, "wrb", "广西");
        User user2 = new User(1, "wry", "广西");
        User user3 = new User(30, "wrg", "广西");
        User[] users = {user, user2, user3};
        // 注意 这么用
        // Arrays.sort(users, new User()); //这样也可以
        Arrays.sort(users, new IdComaprator());
        System.out.println("数组使用");
        for (User u : users) {
            System.out.println(u);
        }
        System.out.println("=======");
        List<User> list = new ArrayList<>();
        list.add(new User(100, "wrb", "广西"));
        list.add(new User(3, "wry", "广西"));
        list.add(new User(10, "wrg", "广西"));
        // 用法2，list sort排序
        // list.sort(new User()); //这样也行
        list.sort(new IdComaprator());
        System.out.println("list使用");
        for (User u : list) {
            System.out.println(u);
        }
        System.out.println();
    }


}

class IdComaprator implements Comparator<User> {

    /**
     * 如果返回负数：第一个参数拍在前面
     * 如果返回正数：第二个参数拍在前面
     * 如果返回0：谁前面无所谓
     *
     * @param o1
     * @param o2
     * @return
     */
    @Override
    public int compare(User o1, User o2) {
        if (o1.getId() >= o2.getId()) {
            return 1;
        }
        return -1;
    }
}

class User implements Comparator<User> {
    public User() {
    }

    public User(int id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    private int id;
    private String name;
    private String address;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public int compare(User o1, User o2) {
        if (o1.getId() >= o2.getId()) {
            return 1;
        }
        return -1;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}
